package br.com.honorato.bean;

import java.io.IOException;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import br.com.honorato.ejb.UserEJB;
import br.com.honorato.exception.EJBServiceException;

@ManagedBean(name = "changePasswordBean")
@ViewScoped
public class ChangePasswordBean extends BaseBean implements Serializable 
{
	private static final long serialVersionUID = 8083861414692863766L;

	private String login;
	private String password;
	private String newPassword;
	private String newPasswordConfirmation;
	
	@EJB
	private UserEJB userEJB;	

	@PostConstruct
	public void init(){

		if (getSessionBean().getLoggedUser()==null)
		{
			try {
				FacesContext.getCurrentInstance().getExternalContext().redirect("../public/login.jsf");
			} catch (IOException e) {
				//TODO logar eero
				e.printStackTrace();
			}
		}else{
			setLogin(getSessionBean().getLoggedUser().getLogin());
		}
	}

	public String changePass() 
	{
		if (newPassword.equals(newPasswordConfirmation))
		{
			try {
				userEJB.changePassword(login, password, newPassword, newPasswordConfirmation);
			} catch (EJBServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				FacesContext.getCurrentInstance().addMessage("",new FacesMessage(e.getMessage()));
			}
		}
		else
		{
			//TODO: recuperar do bundle e melhorar tratamento de erro
			FacesContext.getCurrentInstance().addMessage("",new FacesMessage("Redigitar senha corretamente"));
		}
		
		return "";
	}

	public String getPassword() 
	{
		return password;
	}

	public void setPassword(String password) 
	{
		this.password = password;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getNewPasswordConfirmation() {
		return newPasswordConfirmation;
	}

	public void setNewPasswordConfirmation(String newPasswordconfirmation) {
		this.newPasswordConfirmation = newPasswordconfirmation;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

}